package com.mingqijia.gassafety.job.hangzhou.job;

import com.mingqijia.gassafety.job.hangzhou.service.CityDeviceService;
import com.mingqijia.gassafety.job.hangzhou.service.CityProductService;
import com.mingqijia.gassafety.job.hangzhou.service.HangZhouService;
import com.mingqijia.gassafety.job.hangzhou.service.ThingModelEventService;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.utils.RedisCacheExt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

/**
 * @program: gassafety
 * @description:
 * @author: Mr.Wang
 * @create: 2022-11-30 15:14
 **/


@Configuration
@EnableScheduling
@Slf4j
public class HangZhouJob {

    @Autowired
    RedisCacheExt redisUtil;

    @Autowired
    CityDeviceService cityDeviceService;


    @Autowired
    CityProductService cityProductService;
    @Autowired
    ThingModelEventService thingModelEventService;

    @Autowired
    HangZhouService hangZhouService;


//     * 每天一点,新设备注册


    @Scheduled(cron = "${gassafety.job.hangzhou.registerCityDevice}")
    public void registerCityDevice(){
        log.info("registerCityDevice--start--------");
        String key = Constants.REGISTER_CITY_DEVICE;
        try {
            Boolean acquire = redisUtil.setIfAbsent(key, String.valueOf(System.currentTimeMillis()), Constants.TIME_OUT);//15分钟超时
            if (acquire) {
                cityDeviceService.registerCityDevice();
            }
        }finally {
            redisUtil.del(key);
        }
        log.info("registerCityDevice--end--------");

    }


//     * 根据设备厂商和类型创建新产品
    @Scheduled(cron = "${gassafety.job.hangzhou.createCityProduct}")
    public void createCityProduct(){
        log.info("createCityProduct--start--------");
        String key = Constants.CREATE_CITY_PRODUCT;
        try {
            Boolean acquire = redisUtil.setIfAbsent(key, String.valueOf(System.currentTimeMillis()), Constants.TIME_OUT);//15分钟超时
            if (acquire) {
                cityProductService.createCityProduct();
            }
        } finally {
            redisUtil.del(key);
        }
        log.info("createCityProduct--end--------");

    }

    @Scheduled(cron = "${gassafety.job.hangzhou.createCityThingModel}")
    public void  createCityThingModel(){
        log.info("createCityThingModel--start--------");
        String key = Constants.CREATE_CITY_THING_MODEL;
        try {
            Boolean acquire = redisUtil.setIfAbsent(key, String.valueOf(System.currentTimeMillis()), Constants.TIME_OUT);//15分钟超时
            if (acquire) {
                thingModelEventService.createCityThingModel();
            }
        } finally {
            redisUtil.del(key);
        }
        log.info("createCityThingModel--end--------");
    }


}
